import { loginByUsername, logout, getUserInfo, resetPassword } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import Router from '@/router'
import _ from 'lodash'
const cloneDeep = _.cloneDeep
const user = {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    userInfoStatus: {
      loaded: false
    },
    username: '',
    name: '',
    userId: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setToken(token)
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfoStatus.loaded = true
      state.userInfo = userInfo
      state.name = userInfo.name || userInfo.username
      state.userId = userInfo.userId
    },
    RESET_USER_INFO: (state) => {
      state.userInfoStatus.loaded = false
      state.userInfo = {}
      state.name = ''
      state.userId = ''
    }
  },

  actions: {
    // 用户名登录
    loginByUsername({ commit }, userInfo) {
      const ERR_MSG = '登录失败，请重试'
      var {
        username = '',
        password = ''
      } = userInfo
      return new Promise((resolve, reject) => {
        loginByUsername({ username, password }).then(Response => {
          var {
            code = '',
            data = {},
            msg = ERR_MSG
          } = Response.data || {}
          if (code.toString() === '200') {
            if (data.token) {
              commit('SET_TOKEN', data.token || '')
              // 完善用户信息
              commit('SET_USER_INFO', cloneDeep(data.userInfo))
            }
            resolve(cloneDeep(data))
          } else {
            reject(msg || ERR_MSG)
          }
        }).catch(() => {
          reject(ERR_MSG)
        })
      })
    },

    // 获取用户信息
    getUserInfo({ commit, state }) {
      const ERR_MSG = '用户信息获取失败'
      return new Promise((resolve, reject) => {
        getUserInfo().then(Response => {
          var {
            code = '',
            data = {},
            msg = ERR_MSG
          } = Response.data || {}
          if (code.toString() === '200') {
            // 完善用户信息
            commit('SET_USER_INFO', data)
            resolve(cloneDeep(data))
          } else {
            reject(msg || ERR_MSG)
          }
          resolve(Response)
        }).catch(() => {
          reject(ERR_MSG)
        })
      })
    },

    // 登出
    logOut({ commit, state }) {
      var ERR_MSG = '登出失败，请重试'
      return new Promise((resolve, reject) => {
        logout().then(Response => {
          var {
            code = '',
            // data = {},
            msg = ERR_MSG
          } = Response.data || {}
          if (code.toString() === '200') {
            commit('SET_TOKEN', '')
            commit('RESET_USER_INFO')
            removeToken()
            resolve()
          } else {
            reject(msg || ERR_MSG)
          }
        }).catch(() => {
          reject(ERR_MSG)
        })
      })
    },
    // 修改密码
    resetPassword({ dispatch }, payload = {}) {
      const ERR_MSG = '修改失败，请重试'
      return new Promise((resolve, reject) => {
        resetPassword(payload).then(Response => {
          var {
            code = '',
            // data = {},
            msg = ERR_MSG
          } = Response.data || {}
          if (code.toString() === '200') {
            // dispatch('fedLogOutToLogin')
            resolve()
          } else {
            reject(msg || ERR_MSG)
          }
        }).catch(() => {
          reject(ERR_MSG)
        })
      })
    },
    // 前端 登出
    fedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('RESET_USER_INFO')
        removeToken()
        resolve()
      })
    },
    fedLogOutToLogin({ dispatch }) {
      dispatch('fedLogOut').then(() => {
        Router.push({ name: 'Login' })
      })
    }
  }
}

export default user
